//
// Created by lyc on 2025/3/24.
//
#include "generateAndReadData.h"

using namespace std;


void generateAndSaveData(const string& filename, int numItems, int maxWeight, int maxCapacity) {
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> weightDist(1, maxWeight);
    uniform_int_distribution<> valueDist(1, 100); // 假设价值在 1-100 之间
    uniform_int_distribution<> capacityDist(numItems, maxCapacity); // 至少能装下一个物品

    ofstream file(filename);
    if (!file.is_open()) {
        cerr << "Error opening file: " << filename << endl;
        return;
    }

    // 写入 CSV 文件的头部
    file << "capacity,num_items" << endl;
    file << capacityDist(gen) << "," << numItems << endl; // 随机生成背包容量
    file << "weight,value" << endl;

    // 生成并写入物品数据
    for (int i = 0; i < numItems; ++i) {
        file << weightDist(gen) << "," << valueDist(gen) << endl;
    }

    file.close();
    cout << "Data generated and saved to: " << filename << endl;
}


//
//struct Item {
//    int weight;
//    int value;
//};

bool readData(const string& filename, double& capacity, vector<Item>& items) {
    ifstream file(filename);
    if (!file.is_open()) {
        cerr << "Error opening file: " << filename << endl;
        return false;
    }

    string line;

    // 读取第一行 (头部)
    getline(file, line); // capacity,num_items  (忽略)

    // 读取第二行 (容量和物品数量)
    //第二行直接忽略
    getline(file, line);
    stringstream ss(line);
    string value;
    getline(ss, value, ','); // 读取 capacity
    capacity = stoi(value);
//    getline(ss, value, ','); // 读取 num_items
//    numItems = stoi(value);

    // 读取第三行 (头部)
    getline(file, line); // weight,value (忽略)


    // 读取物品数据
    int id_count = 1;
    while (getline(file, line)) {
        stringstream ss(line);
        string weightStr, valueStr;
        getline(ss, weightStr, ',');
        getline(ss, valueStr, ',');

        Item item;
        item.weight = stoi(weightStr);
        item.value = stoi(valueStr);
        item.id = id_count++;

        items.push_back(item);
    }

    file.close();
    return true;
}

